package com.by.basicweb.filter;

import com.by.toolkit.consts.WebGlobalConst;
import com.by.toolkit.platform.ByContext;
import com.by.toolkit.utils.RequestIdUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * 请求id过滤器
 *
 * @author YanBingHao
 * @since 2025/9/30
 */
@Slf4j
@Order(Integer.MIN_VALUE-1)
@Component
public class RequestIdFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String requestURI = request.getRequestURI();
        String requestId = request.getHeader(WebGlobalConst.REQUEST_ID);
        RequestIdUtil.requestStart(requestId);
        log.info("[RequestIdFilter][doFilter] requestURI:[{}] requestId:[{}]", requestURI, requestId);
        try {
            filterChain.doFilter(servletRequest, servletResponse);
        } finally {
            RequestIdUtil.requestEnd();
            ByContext.remove();
        }
    }

}
